module app.controller.admin.UserController;

import hunt.framework;
import app.repository.UserRepository;
import app.response.ResultMsg;
import app.utils.RespCodeEnun;
import app.model.User;
import std.json;
import app.middleware.CheckIdValidity;

class UserController : Controller
{
    mixin MakeController;

    /*
    * 用户列表
    */
    @Action Response userlist()
    {
        UserRepository userRepository = new UserRepository();
        ResultMsg resultMsg = new ResultMsg();

        User[] users = userRepository.findAll();
        JSONValue[] items;
        foreach (user; users)
        {
            JSONValue item;
            item["id"] = user.id;
            item["username"] = user.username;
            item["role"] = user.role;
            items ~= item;
        }
        resultMsg.code = RespCodeEnun.SUCCESS;
        resultMsg.msg = "success";
        resultMsg.data["data"] = items;
        return new JsonResponse(resultMsg);
    }

    /**
    * 更新
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response update(long id)
    {
        import std.conv : to;
        import std.digest : toHexString;
        import std.digest.md : MD5Digest;
        import std.uni : toLower;

        UserRepository userRepository = new UserRepository();
        ResultMsg resultMsg = new ResultMsg();

        // 接收提交来的json数据
        JSONValue updateJson = request.json();

        try
        {
            User user = userRepository.findById(id);
            user.username = updateJson["username"].str;
            user.password = toLower(toHexString(new MD5Digest().digest(updateJson["password"].str)));
            user.role = to!uint(updateJson["role"].integer);
            // 更新
            userRepository.save(user);
            resultMsg.code = RespCodeEnun.SUCCESS;
            resultMsg.msg = "success";
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统错误";
        }
        return new JsonResponse(resultMsg);
    }

    /**
    * 详情
    */
    @Middleware(CheckIdValidity.stringof)  // id参数检查中间件
    @Action Response detail(long id)
    {
        UserRepository userRepository = new UserRepository();
        ResultMsg resultMsg = new ResultMsg();

        User user = userRepository.findById(id);
        if (user is null)
        {
            this.response.setStatus(404);
            return new JsonResponse(new ResultMsg(RespCodeEnun.Not_Found, "用户未找到"));
        }

        JSONValue item;
        item["id"] = user.id;
        item["username"] = user.username;
        item["role"] = user.role;

        resultMsg.code = RespCodeEnun.SUCCESS;
        resultMsg.msg = "success";
        resultMsg.data["data"] = item;
        return new JsonResponse(resultMsg);
    }
}
